import React from 'react'
import Link from 'next/link'
import Layout from './Layout'
import ListItem from './ListItem'
import { Card, Alert, Modal } from 'antd'
import { inject, observer } from 'mobx-react'
import Masonry from 'react-masonry-component'
import LazyLoad from 'react-lazyload'

const Meta = Card.Meta

@inject('store') @observer
export default class List extends React.Component {
  constructor (props) {
    super(props)

    this.state = {
      currentPage: 1,
      hasMore: false,
      showImages: false,
      dialogImageVisible: false,
      largeImage: ''
    }

    this.handleScroll = this.handleScroll.bind(this)
    this.handleLoadMore = this.handleLoadMore.bind(this)
  }

  componentDidMount () {
    window.addEventListener('scroll', this.handleScroll)
    this.handleLayoutComplete()
  }

  componentWillUnmount () {
    window.removeEventListener('scroll', this.handleScroll)
  }

  handleScroll () {
    if (document.documentElement.offsetHeight + document.documentElement.scrollTop > document.documentElement.scrollHeight - 50) {
      this.querySearchResult();
    }
  }

  querySearchResult(){
    if (this.state.hasMore) {
      return;
    }
    setTimeout(this.handleLoadMore, 1000);
    this.setState({ hasMore: true })
  }

  async handleLoadMore () {
    this.setState((prevState) => ({
      currentPage: prevState.currentPage + 1
    }))
    
    const currentPage = this.state.currentPage
    const apiUrl = this.props.apiUrl

    const res = await fetch(`${apiUrl}${currentPage}`)
    const json = await res.json()
    if(this.props.title === '图片'){
      if (json.response[0].works && json.response.length) {
        this.props.store.loadMoreList(json.response[0].works)
        this.setState({ hasMore: false })
      } else {
        this.setState({ hasMore: false })
      }
    }else{
      if (json.results && json.results.length) {
        this.props.store.loadMoreList(json.results)
        this.setState({ hasMore: false })
      } else {
        this.setState({ hasMore: false })
      }
    }
  }

  handleLayoutComplete () {
    this.setState({
      showImages: true
    })
  }

  handleLargeImageShow (url) {
    this.setState({
      dialogImageVisible: true,
      largeImage: url
    })
  }

  handleLargeImageHide () {
    this.setState({
      dialogImageVisible: false
    })
  }

  render () {
    let list = this.props.store.list

    const childNormalElements = list.map(item =>
      <ListItem item={item} key={item._id}></ListItem>
    )

    const childImageElements = list.map(element =>
      <div
        style={{ width: '25%', boxSizing: 'border-box', padding: 20 }}
        key={element._id}
        onClick={() => this.handleLargeImageShow(element.url)}
      >
        <Card cover={<img src={`${element.url}?imageView2/2/w/436`} />} hoverable>
          <Meta
            title={element.desc}
          />
        </Card>
      </div>
    )

    return (
      <Layout title={this.props.title}>
        {
          this.props.title === '福利'
            ? <div style={{ opacity: this.state.showImages ? '1' : '0', transition: 'opacity 0.5s linear' }}>
                <Masonry>
                  {childImageElements}
                </Masonry>
              </div>
            : this.props.title === '图片' ? 
              <Masonry>
                {
                  list.map((element, i) => {
                    const item = element.work
                    const imgHeight = item.height * 208 / item.width
                    return <div
                      style={{ width: '25%', boxSizing: 'border-box', padding: 20 }}
                      key={`${item.id}+s${i}`}
                      onClick={() => this.handleLargeImageShow(item.image_urls.px_480mw)}
                    >
                      <Card cover={<LazyLoad throttle={200} height={imgHeight}><img src={`${item.image_urls.px_480mw}`} style={{height: imgHeight}} /></LazyLoad>} hoverable>
                        <Meta
                          title={item.title}
                        />
                      </Card>
                    </div>
                    }
                  )
                }
              </Masonry> : childNormalElements
        }

        <Modal
          title="原图"
          visible={this.state.dialogImageVisible}
          wrapClassName="vertical-center-modal"
          footer={null}
          onCancel={() => this.handleLargeImageHide()}
        >
          <img style={{ maxWidth: '100%' }} src={this.state.largeImage} />
        </Modal>

        {
          this.state.hasMore
            ? (<Card loading bordered={false} style={{ width: '100%' }}>loading card</Card>)
            : (<Alert message="全部列表都在这，没有更多了~" type="info" showIcon />)
        }
      </Layout>
    )
  }
}
